//axios基础的封装
import axios from "axios"
import { ElMessage } from "element-plus"
import "element-plus/theme-chalk/el-message.css"
import { useUserStore } from "@/stores/user"
import { useFunctionTreeStore } from "@/stores/functionTree"
// import {useRouter} from 'vue-router'
import router from "@/router/index"

//axios基础封装1（默认）
const httpInstance1 = axios.create({
  //配置基地址
  baseURL: "http://localhost:8080/",
  // baseURL: "http://admin.mi9688.top/api/",
  // baseURL: "http://8.130.132.45:8080/",
  //配置超时时间
  timeout: 20000,
})

// axios请求拦截器
httpInstance1.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    const token = userStore.userInfo.token;
    // console.log("请求拦截器得到token：" + token);
    config.headers["Content-Type"] = "application/json";
    if (token) {
      config.headers.Authorization = "Bearer " + token;
    }
     eval()
    return config;
  },
  (e) => Promise.reject(e)
)

// axios响应式拦截器
httpInstance1.interceptors.response.use(
  (res) => res.data,
  (e) => {
    console.log("响应拦截器：")
    console.log(e.response.data)
    //统一错误提示
    if (e.response.status === 400) {
      ElMessage({
        type: "error",
        message: e.response.data.message,
      })
      return e.response.data
    }
    //token失效401处理
    if (e.response.status === 401) {
      const userStore = useUserStore()
      const functionTreeStore = useFunctionTreeStore()
      userStore.clearUserInfo()
      functionTreeStore.clearFunctionTreeInfo()
      ElMessage({
        type: "error",
        message: "登录已过期!",
      });
      router.push("/login")
    }
    //404处理
    if (e.response.status === 404) {
      ElMessage({
        type: "error",
        message: "未找到功能接口",
      })
    }

    if (e.response.status === 408) {
      ElMessage({
        type: "error",
        message:'请求超时！',
      })
      return Promise.reject(e)
    }
    //服务器错误处理
    if (e.response.status === 500) {
      ElMessage({
        type: "error",
        message: "系统错误！",
      })
    }
    return Promise.reject(e)
  }
);

export default httpInstance1
